﻿using Bridge.Workflow.Domain;
using Bridge.Workflow.Workflows.Dtos;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bridge.Workflow.WorkflowCore
{
    /// <summary>
    /// 节点的处理者，封装所有节点处理的业务逻辑
    /// </summary>
   public  class NodeProcessor
    {
        public PersistedWorkflow _workflow { get; set; }
        public WorkflowNode _currentNode { get; set; }
        public WorkflowAuditInput _audit { get; set; }
        public PersistedExecutionPointer _pointer { get; set; }
        public BaseApprovalOption _option { get; set; }
        public NodeProcessor(PersistedWorkflow workflow, WorkflowNode currentNode, WorkflowAuditInput audit, PersistedExecutionPointer pointer, BaseApprovalOption option) {

            this._workflow = workflow;
            this._currentNode = currentNode;
            this._audit = audit;
            this._pointer = pointer;
            this._option = option;
        }
        public NodeProcessor() { }
        public string GetNextNodeKey()
        {
            var nextNodeKey = string.Empty;
            var nextNode = _currentNode.NextNodes.FirstOrDefault(a => a.Label == _audit.OperateName);
            //如果没有明确驳回给谁则谁送审的就驳回给谁
            if(nextNode == null && _audit.OperateName == OperateNameEnum.驳回.ToString())
            {
                return this._pointer.SourceKey;
            }
            nextNodeKey = nextNode?.NodeId;
            if (!this._option.IsSelectCondition)
            {
                return nextNodeKey;
            }

            string selectConditionNodeKey = GetNextNodeKeyByConditions(nextNode);

            if (!string.IsNullOrEmpty(selectConditionNodeKey))
            {
                nextNodeKey = selectConditionNodeKey;
            }

            return nextNodeKey;
        }
        private string GetNextNodeKeyByConditions(WorkflowConditionNode nextNode)
        {
            WorkflowData BusinessData = JsonConvert.DeserializeObject<WorkflowData>(_workflow?.Data);
            var selectConditionNodeKey = string.Empty;
            if (!nextNode.Conditions.Any())
            {
                return selectConditionNodeKey;
            }
            
                //依次匹配条件，如果有一个满足就选择
                foreach (var item in nextNode.Conditions)
                {
                  IConditionProcess process = ConditionFactory.CreateProcess(item);
                if (process != null)
                {
                   string conditionNodeKey = process.ExecuteResult(BusinessData);
                    if (!string.IsNullOrEmpty(conditionNodeKey))
                    {
                        selectConditionNodeKey = conditionNodeKey;
                        break;
                    }
                }

                }
            return selectConditionNodeKey;


        }
    }
}
